package com.bc.wallpaper;

import java.util.HashMap;
import java.util.List;
import java.util.Timer;

import com.bc.R;
import com.bc.db.entity.BtcNews;
import com.bc.service.deal.BtcCategory;
import com.bc.ui.BtcCacheOperator;
import com.bc.ui.BtcService;
import com.bc.ui.MainActivity;
import com.bc.utils.CommonUtils;
import com.bc.utils.Constants;
import com.bc.utils.SettingPrefs;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.service.wallpaper.WallpaperService;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.TextView;

public class BtcWallPaperService extends WallpaperService {

	@Override
	public void onCreate() {
		super.onCreate();
		if (!BtcService.started) {
			Log.d(getClass().getSimpleName(), "BtcService has not started...");
			Intent intent = new Intent(BtcWallPaperService.this, BtcService.class);
			startService(intent);
		}
	}
	
	@Override
	public Engine onCreateEngine() {
		
		return new BtcEngine();
	}
	
	public class BtcEngine extends Engine implements SharedPreferences.OnSharedPreferenceChangeListener{
		private SharedPreferences mPreferences;
		private final Paint mPaint = new Paint();
		private Handler mHandler = new Handler();
		private int screenWidth, screenHeight;
		private Timer mTimer;
		private int fontSize = 25;//字体大小
		private int markDrawableWidth = 25;
		private int markDrawableHeight = 25;
		private int btcImageWidth = CommonUtils.dip2px(BtcWallPaperService.this, 50);
		private int btcImageHeght = btcImageWidth - 15;
		private int btcTopMargin = 90;
		
		private Bitmap downBmp, upBmp, wallpaperBmp;
		private BtcCacheOperator mBtcCacheOperator;
		private HashMap<String, Bitmap> mCacheHashMap = new HashMap<String, Bitmap>();
		public final DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
				.cacheOnDisc(true).imageScaleType(ImageScaleType.EXACTLY).build();
		
		public BtcEngine() {
			mBtcCacheOperator = BtcCacheOperator.getInstance();
			
			mPaint.setColor(Color.WHITE);
			mPaint.setAntiAlias(true);
			mPaint.setStrokeWidth(1);
//			mPaint.setStrokeCap(Paint.Cap.ROUND);
			mPaint.setStyle(Paint.Style.STROKE);
			mPaint.setTextAlign(Align.CENTER);
			mPaint.setTextSize(30);
			mPreferences = SettingPrefs.getInstance(BtcWallPaperService.this).getPreferences();
			mPreferences.registerOnSharedPreferenceChangeListener(this);
			
			screenWidth = getResources().getDisplayMetrics().widthPixels;
			screenHeight = getResources().getDisplayMetrics().heightPixels;
			
			wallpaperBmp = BitmapFactory.decodeResource(getResources(), R.drawable.wallpaper);
//			ImageLoader.getInstance().loadImage("drawable://" + R.drawable.wallpaper, new ImageSize(screenWidth, screenHeight), new SimpleImageLoadingListener(){
//				@Override
//				public void onLoadingComplete(String imageUri, View view,
//						Bitmap loadedImage) {
//					wallpaperBmp = loadedImage;
//				}
//			});
			downBmp = BitmapFactory.decodeResource(getResources(), R.drawable.down);
			upBmp = BitmapFactory.decodeResource(getResources(), R.drawable.up);
			markDrawableHeight = downBmp.getHeight();
			markDrawableWidth = downBmp.getWidth();
			
		}
		
		@Override
		public void onTouchEvent(MotionEvent event) {
			super.onTouchEvent(event);
		}

		@Override
		public void onCreate(SurfaceHolder surfaceHolder) {
			super.onCreate(surfaceHolder);
			this.setTouchEventsEnabled(true);
		}
		
		@Override
		public void onSurfaceChanged(SurfaceHolder holder, int format,
				int width, int height) {
			super.onSurfaceChanged(holder, format, width, height);
		}

		@Override
		public void onOffsetsChanged(float xOffset, float yOffset,
				float xOffsetStep, float yOffsetStep, int xPixelOffset,
				int yPixelOffset) {
			drawWallpaper();
		}
		
		public void onVisibilityChanged(boolean visible) {
			if (visible) {
				mHandler.postDelayed(runnable, 300);
			} else {
				mHandler.removeCallbacks(runnable);
			}
		};
		
		public void drawWallpaper() {
			SurfaceHolder holder = getSurfaceHolder();
			Canvas canvas = null;
			
			try {
				canvas = holder.lockCanvas();
				drawBtcRefreshFrame(canvas);
			} finally {
				if (canvas != null) {
					holder.unlockCanvasAndPost(canvas);
				}
			}
			mHandler.removeCallbacks(runnable);
			mHandler.postDelayed(runnable, 30000);
		}
		
		public void drawBtcRefreshFrame(Canvas canvas) {
			if (canvas == null) {
				return;
			}
			int left = Math.abs(screenWidth - wallpaperBmp.getWidth()) / 2;
			int top = Math.abs(screenHeight - wallpaperBmp.getHeight()) / 2;
//			canvas.drawBitmap(wallpaperBmp, left, top, null);
			canvas.drawBitmap(wallpaperBmp, 0, 0, mPaint);
//			canvas.drawBitmap(wallpaperBmp, new Rect(left, top, left + screenWidth, top + screenHeight), new Rect(0, 0, screenWidth, screenHeight), mPaint);
			List<BtcNews> btcNewsList = mBtcCacheOperator.getEnabledBtcNews();
			List<BtcCategory> btcCategories = mBtcCacheOperator.getBtcCategories();
			if (btcNewsList.size() != btcCategories.size()) {
				return;
			}
			mCacheHashMap.clear();
			for (final BtcNews bc : btcNewsList) {
				if (bc != null) {
					ImageLoader.getInstance().loadImage("assets://" + bc.btcIcon.trim() +".png", new ImageSize(100, 100), new SimpleImageLoadingListener(){
						@Override
						public void onLoadingComplete(String imageUri,
								View view, Bitmap loadedImage) {
							Log.d(getClass().getSimpleName(), "imageName: " + bc.btcIcon.trim()+".png");
							mCacheHashMap.put(bc.btcType, loadedImage);
						}
					});
				}
			}
			canvas.save();
			canvas.translate(btcImageWidth, 0);
			Log.d(getClass().getSimpleName(), "btcImageWidth: " + btcImageWidth);
			canvas.drawText(getResources().getString(R.string.last_buy_text), btcImageWidth, btcTopMargin, mPaint);
			int textWidth = (screenWidth - btcImageWidth) / 3;
			canvas.drawText(getResources().getString(R.string.buy_one_text), btcImageWidth + textWidth, btcTopMargin, mPaint);
			canvas.drawText(getResources().getString(R.string.sell_one_text), btcImageWidth + 2 * textWidth, btcTopMargin, mPaint);
			canvas.restore();
			canvas.translate(0, 10);
			for (int i = 0; i < btcNewsList.size(); i++) {
				BtcCategory btcCg = btcCategories.get(i);
				if (btcCg != null) {
					String type = btcCg.getBtcType();
					HashMap<String, Object> hashMap = btcCg.getBtcNews();
					if (mCacheHashMap.get(type)!= null) {
						canvas.drawBitmap(mCacheHashMap.get(type), 0, btcImageHeght* (i + 1) , mPaint);
					} else {
						Log.d(getClass().getSimpleName(), "type bitmap is null...");
					}
					canvas.save();
					canvas.translate(btcImageWidth, 0);
					Object lastObject = hashMap.get(Constants.LAST_SALE_PRICE);
					String lastSale = CommonUtils.ToString(lastObject);
					
					int drawHeight =  (int) (mPaint.getTextSize() + btcImageHeght * (i+1) + (btcImageHeght - mPaint.getTextSize()) / 2);
					if (!TextUtils.isEmpty(lastSale)) {
						lastSale = CommonUtils.DisplayFormatString(type, lastSale, BtcWallPaperService.this);
						canvas.drawText(lastSale, btcImageWidth, drawHeight, mPaint);
						
//						BtcCategory bCategory = mBtcCacheOperator.getBtcCategoryFromMap(btcCg.getBtcType());
//						HashMap<String, Object> lastDataHashMap = bCategory != null ? bCategory.getBtcNews() : null;
//						if (lastDataHashMap != null) {
//							Object oldObj = lastDataHashMap.get(Constants.LAST_SALE_PRICE);
//							getMarkBitmap(lastObject, oldObj);
//						}
					}
					
					Object buyObject = hashMap.get(Constants.BUY_ONE_PRICE);
					String buyPrice = CommonUtils.ToString(buyObject);
					if (!TextUtils.isEmpty(buyPrice)) {
						buyPrice = CommonUtils.DisplayFormatString(type, buyPrice, BtcWallPaperService.this);
						canvas.drawText(lastSale, btcImageWidth + textWidth, drawHeight, mPaint);
					}
					
					Object sellObject = hashMap.get(Constants.SELL_ONE_PRICE);
					String sellPrice = CommonUtils.ToString(sellObject);
					Log.d(getClass().getSimpleName(), "sellPrice: " + sellPrice);
					if (!TextUtils.isEmpty(sellPrice)) {
						sellPrice = CommonUtils.DisplayFormatString(type, sellPrice, BtcWallPaperService.this);
						canvas.drawText(sellPrice, btcImageWidth + 2 * textWidth, drawHeight, mPaint);
					} 
					canvas.restore();
				}
				
			}
//			canvas.restore();
//			if (canvas != null) {
//				canvas.save();
//				canvas.drawText("hello world", 100, 100, mPaint);
//				canvas.restore();
//			}
		}
		
		public Runnable runnable = new Runnable() {
			
			@Override
			public void run() {
				drawWallpaper();
			}
		};
		
		@Override
		public void onSurfaceCreated(SurfaceHolder holder) {
			super.onSurfaceCreated(holder);
		}

		@Override
		public void onSurfaceDestroyed(SurfaceHolder holder) {
			super.onSurfaceDestroyed(holder);
		}

		@Override
		public void onSharedPreferenceChanged(
				SharedPreferences sharedPreferences, String key) {
			
		}
		
		public Bitmap getMarkBitmap(Object newObj, Object oldObj) {
			if (CommonUtils.BigThan(newObj, oldObj) < 0) {
				return downBmp;
			} else if (CommonUtils.BigThan(newObj, oldObj) > 0) {
				return upBmp;
			} else {
				return null;
			}
		}
		
	}
}
